﻿using Firefly.ExtensionMethods;
using Firefly.Framework.ContentManagement;
using Firefly.Framework.Components;
using Firefly.Framework.Input;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

namespace Firefly.Framework.Windows
{    
    public class Cursor : DrawableComponent, IPipelineSerializeable
    {
        private Texture2D _texture;

        public string AssetName { get; set; }
        public Point Offset { get; set; }
        [ContentSerializer(Optional = true)]
        public Color Color { get; set; }

        public Cursor()
        {
            Visible = true;
            Enabled = true;
            Color = Color.White;
        }

        #region IHasContent Members

        public override void LoadContent()
        {
            _texture = ContentService.Instance.Load<Texture2D>(WindowsService.Instance.ThemePath + AssetName);
        }

        public override void UnloadContent()
        {
            ContentService.Instance.Release(WindowsService.Instance.ThemePath + AssetName);
        }

        #endregion

        #region IUpdateable Members

        public override void Update(GameTime gameTime)
        {
            if (Enabled)
            {
            }
        }

        #endregion

        #region IDrawable Members

        public override void Draw(GameTime gameTime)
        {
            if (Visible)
            {
                Point position = InputService.Instance.MouseManager.CurrentAxisPosition.ToPoint();
                WindowsService.Instance.SpriteBatch.Draw(_texture,
                    new Vector2(position.X - Offset.X, position.Y - Offset.Y), 
                    Color);
            }
        }

        #endregion

        #region IPipelineSerializeable Members

        public void DeserializeContent(ContentReader input)
        {
            AssetName = input.ReadString();
            Offset = input.ReadObject<Point>();
            Color = input.ReadObject<Color>();
            LoadContent();
        }

        #endregion

        #region IDisposable Members

        protected override void Dispose(bool disposing)
        {
            if (!Disposed)
            {
                if (disposing)
                {
                    UnloadContent();
                }

                Disposed = true;
            }
        }

        ~Cursor()
        {
            Dispose(false);
        }

        #endregion
    }    
}
